/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.com.smart.hawk.view.impl;

import co.com.smart.hawk.controller.HawkSitiosCtrl;
import co.com.smart.hawk.dto.SitiosDTO;
import co.com.smart.hawk.utilities.HawkTableMgr;
import co.com.smart.hawk.utilities.HawkViewMgr;
import co.com.smart.hawk.utilities.Utility;
import co.com.smart.hawk.view.HawkSitiosView;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.math.BigDecimal;
import java.util.List;
import javax.swing.*;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;

/**
 *
 * @author Ceyni Paola
 */
public class HawkSitiosViewImpl extends javax.swing.JInternalFrame implements HawkSitiosView {

    private HawkSitiosCtrl controller;
    private HawkTableMgr<SitiosDTO> tableMgr;

    /**
     * Creates new form HawkSitiosViewImpl
     */
    public HawkSitiosViewImpl(JDesktopPane desktopPane, HawkSitiosCtrl hawkSitiosCtrl) {

        if (HawkViewMgr.getInstance().getObjectInstance(this.getClass()) == null) {
            try {
                this.controller = hawkSitiosCtrl;
                initComponents();
                this.initEvent();
                this.initComponentsSitios();
                //this.consultarArticulos();
                java.awt.Dimension dimension = desktopPane.size();
                java.awt.Dimension ventan = this.getSize();
                this.setLocation(new java.awt.Point((dimension.width - ventan.width) / 2, (dimension.height - ventan.height) / 2));
                HawkViewMgr.getInstance().setObjectInstance(this);
            } catch (Throwable ex) {
                ex.printStackTrace();
            }

        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jL_codigo = new javax.swing.JLabel();
        jL_descripcion = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        txtDescripcionSitio = new javax.swing.JTextField();
        txtscsitio = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbSitios = new javax.swing.JTable();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("SmartHawk-Sitos");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/img/smart-jungle.png"))); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.setMinimumSize(new java.awt.Dimension(0, 0));

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel2.setMinimumSize(new java.awt.Dimension(0, 0));
        jPanel2.setPreferredSize(new java.awt.Dimension(295, 52));

        jLabel1.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N
        jLabel1.setText("Sitios");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/guardar.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/limpiar.png"))); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/consultar.png"))); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jButton1))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 0, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jL_codigo.setText("Código*");

        jL_descripcion.setText("Descripción*");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jL_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32)
                .addComponent(jL_descripcion)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtDescripcionSitio, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jL_codigo)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jL_descripcion)
                    .addComponent(txtDescripcionSitio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        txtscsitio.setText("jTextField1");

        tbSitios.setBorder(javax.swing.BorderFactory.createTitledBorder("Lista sitios"));
        tbSitios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Descripción", ""
            }
        ));
        tbSitios.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tbSitios);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 644, Short.MAX_VALUE)
                            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(151, 151, 151)
                        .addComponent(txtscsitio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(txtscsitio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE)
                .addGap(45, 45, 45))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        getAccessibleContext().setAccessibleName("SmartHawk-Sitios");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        grabarSitios();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        limpiarFormulario();
    }//GEN-LAST:event_jButton2ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jL_codigo;
    private javax.swing.JLabel jL_descripcion;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbSitios;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextField txtDescripcionSitio;
    private javax.swing.JTextField txtscsitio;
    // End of variables declaration//GEN-END:variables

    @Override
    public void initEvent() {
        this.addInternalFrameListener(new InternalFrameAdapter() {

            @Override
            public void internalFrameClosing(InternalFrameEvent e) {
                SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

                    @Override
                    protected Void doInBackground() throws Exception {
                        return null;
                    }

                    @Override
                    protected void done() {
                        cancelarProceso();
                    }
                };
                worker.execute();
            }
        });
    }

    @Override
    public void grabarSitios() {
        if (validarCampos()) {
            try {
                SitiosDTO sendObject = new SitiosDTO();

                sendObject.setScsitios(new BigDecimal(txtCodigo.getText()));
                sendObject.setCositios(txtCodigo.getText());
                sendObject.setDssitios(txtDescripcionSitio.getText());

                controller.grabarSitios(new Utility.CallBackSmartHawk<SitiosDTO>() {

                    @Override
                    public void endProcess(SitiosDTO object) {
                        JOptionPane.showMessageDialog(HawkSitiosViewImpl.this, object.getDsmensaje(), "Información", JOptionPane.INFORMATION_MESSAGE);
                        // limpiarFormulario();
                    }
                }, sendObject);

                listarSitios();
            } catch (Throwable thr) {
                JOptionPane.showMessageDialog(this, "Error almacenado el sitio: \n" + thr.getMessage(), "Error procesando", JOptionPane.ERROR_MESSAGE);
                return;
            }

        }
    }

    /**
     * valida los campos obligatorios para la vista
     *
     * @return
     */
    private boolean validarCampos() {
        boolean flag = true;

        if (txtCodigo == null || "".equals(txtCodigo.getText()) && flag) {
            JOptionPane.showMessageDialog(this, "El código es obligatorio", "Validación", JOptionPane.WARNING_MESSAGE);
            flag = false;
            txtCodigo.grabFocus();
        }

        if (txtDescripcionSitio == null || "".equals(txtDescripcionSitio.getText()) && flag) {
            JOptionPane.showMessageDialog(this, "La descripcion es obligatorio", "Validación", JOptionPane.WARNING_MESSAGE);
            flag = false;
            txtDescripcionSitio.grabFocus();
        }


        return flag;
    }

    @Override
    public void cancelarProceso() {
        int message = JOptionPane.showConfirmDialog(this, "Está seguro que desea salir?", "Salir", JOptionPane.YES_NO_OPTION);
        if (message == JOptionPane.YES_OPTION) {
            HawkViewMgr.getInstance().removeObjectInstance(this.getClass());
            System.gc();
            this.dispose();
        }
    }

    @Override
    public void initComponentsSitios() {
        try {

            txtscsitio.setVisible(false);
            txtscsitio.setText("0");
                    tableMgr = new HawkTableMgr<>(tbSitios);
        tableMgr.setPosition(HawkTableMgr.PositionObject.LAST);
            JLabel buscar = new JLabel(new ImageIcon(getClass().getResource("/img/search_grid.png")));
            buscar.addMouseListener(new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent e) {
                    try {
                        SitiosDTO sitios = tableMgr.getSelectObject();
                        txtscsitio.setText(sitios.getScsitios().toString());
                        txtCodigo.setText(sitios.getCositios());
                        txtDescripcionSitio.setText(sitios.getDssitios());
                    } catch (Throwable ex) {
                        ex.printStackTrace(System.err);
                    }
                }
            });
            tableMgr.addNewValueColumn(buscar);
            listarSitios();

        } catch (Throwable ex) {
            ex.printStackTrace(System.err);
        }
    }

    @Override
    public void listarSitios() throws Throwable {
        controller.consultarSitios(new Utility.CallBackSmartHawk<List<SitiosDTO>>() {

            @Override
            public void endProcess(List<SitiosDTO> object) {
                try {
                    tableMgr.clearAll();
                    tableMgr.setData(object);
                } catch (Throwable ex) {
                    ex.printStackTrace(System.err);
                    JOptionPane.showMessageDialog(HawkSitiosViewImpl.this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                }

            }
        });
    }

    public void limpiarFormulario() {
        txtCodigo.setText("");
        txtDescripcionSitio.setText("");
        txtscsitio.setText("0");

    }
}
